package com.book.book.service;

import com.book.book.domain.BookInfo;
import com.book.book.mapper.BookInfoMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;

@Service
public class BookInfoService {
    @Autowired
    BookInfoMapper bookInfoMapper;
    public PageInfo getPage(BookInfo bookInfo, Integer pagenum) {
        PageHelper.startPage(pagenum, 5,"bookId desc");
        List<BookInfo> list = bookInfoMapper.selectBy(bookInfo);

        return new PageInfo(list);
    }

    public void saveOrUpdate(BookInfo bookInfo) {
        // 处理价格字段：若为空，设置默认值（例如 0.0）
        if (bookInfo.getBookprice() == null) {
            bookInfo.setBookprice(BigDecimal.valueOf(0.0)); // 设置默认价格
        }
        if (bookInfo.getIsborrowed() == null) {
            bookInfo.setIsborrowed(0); // 默认未借出
        }

        if (bookInfo.getBookid() == null) {
            bookInfoMapper.insert(bookInfo);
        } else {
            // 更新场景：仅更新非空字段（原逻辑）
            bookInfoMapper.updateByPrimaryKeySelective(bookInfo);
        }
    }

    public Boolean validateBookname(String bookname, Long bookid) {
        //特殊情况，修改的时候用户没修改apk名称
        if(bookid != null){
            BookInfo bookInfo1 = bookInfoMapper.selectByPrimaryKey(bookid);
            if(bookInfo1 != null && bookInfo1.getBookname().equals(bookname)){ // 增加 null 检查
                return true;
            }
        }

        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookname(bookname);
        List<BookInfo> list = bookInfoMapper.selectBy(bookInfo);
        if(list==null||list.size()==0){
            return true;
        }else{
            return false;
        }
    }

    public BookInfo getById(Long bookid) {
        return  bookInfoMapper.selectByPrimaryKey(bookid);
    }

    @Transactional(rollbackFor = Exception.class)
    public void del(Long bookid, String uploadPath) {
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(bookid);
        if(bookInfo != null && bookInfo.getBookimg()!=null){ // 增加 null 检查
            File logo = new File(uploadPath+bookInfo.getBookimg());
            if(logo.exists()){ // 检查文件是否存在再删除
                logo.delete();
            }
        }
        bookInfoMapper.deleteByPrimaryKey(bookid);
    }

    // 检查图书是否可借阅 (即isborrowed为0)
    public Boolean checkBookBorrowable(Long bookid) {
        BookInfo bookInfo = bookInfoMapper.selectByPrimaryKey(bookid);
        // 确保图书存在且 isBorrowed 为 0
        return bookInfo != null && bookInfo.getIsborrowed() != null && bookInfo.getIsborrowed() == 0; // 0 表示未借出，可借阅
    }

}